# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>

from excavator.utils.file import write
from excavator.db.meta.model import Model
from excavator.db.meta.fields import CharField, ListField, ModelField


class Level(object):
    # 检测的通知信息
    info = "info"
    # 检测的故障信息，如果存在故障，则检测流程失败
    error = "error"


# 重置errors 为reports,方便生成报告信息

class ReportModel(Model):
    msg = CharField()
    level = CharField()
    job = CharField()


class ReportsModel(Model):
    reports = ListField(ModelField(ReportModel))


def notify_info(msg, name, level=Level.info):
    reports_obj = ReportsModel.get()
    reports = []
    if reports_obj is not None:
        reports = reports_obj.reports
    report = ReportModel(msg=str(msg), job=name, level=level)
    reports.append(report)
    ReportsModel.create(reports=reports)


def notify_err(msg, name):
    notify_info(msg, name, level=Level.error)


def save_report(filename):
    body = ""
    is_err = False
    reports = ReportsModel.get()
    for report in reports.reports:
        if report.level == Level.error and not is_err:
            is_err = True
        body += "{} -- {} : {}\n".format(report.job, report.level, report.msg)

    write(filename, body)
    return is_err
